<?php

namespace qcloud;

use Qcloud\Cos\Client;
use think\facade\Env;
use think\facade\Log;

class OssQCloud {
    /**
     * 构造函数
     * Oss constructor.
     */
    public function __construct() {
        require 'vendor/autoload.php';
    }

    /***
     * @desc 将本地图片上传到远程服务器
     * @param $fileName
     * @param $pathName
     * @return mixed|string
     */
    public function uploadImage($fileName, $pathName,$flag,$cdn = 'NO') {
        $cosClient = new Client(array(
            'region' => Env::get('ossqcloud.oss_region'),
            'credentials' => array(
                'appId' => Env::get('ossqcloud.app_id'),
                'secretId' => Env::get('ossqcloud.secret_id'),
                'secretKey' => Env::get('ossqcloud.secret_key'),
            ),
        ));
        // 若初始化 Client 时未填写 appId，则 bucket 的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        $bucket = Env::get('ossqcloud.bucket');

        try {
            $result = $cosClient->Upload(
                $bucket = $bucket,
                $key = $fileName,
                $body = fopen($pathName, 'rb')
            );

            $url = $result['Location'];
            if ($cdn == 'YES'){
                $url = str_replace('http://'.$bucket."-".Env::get('ossqcloud.app_id').'.cos.'.Env::get('ossqcloud.oss_region').'.myqcloud.com', Env::get('oss.url'), $url);
            }
            $url = urldecode($url);

            return $url;
        } catch (\Exception $e) {
            Log::write("上传本地图片到OssQCloud服务器错误信息" . print_r($e));
        }
    }
}